<?php
/**
 * TinyCatPHP 极简、快速、创新、易用、高性能的PHP应用开发框架
 * User: CnTaiGe <hst042@163.com>
 * Date: 2017/11/19
 */

namespace TinyCatPHP\libs\utils;
class Running
{
    protected static $times;
    protected static $memory;

    /**
     * 获取运行时内存
     * @param bool $isByte
     * @return int|string
     */
    public static function getMemory($isByte = false)
    {
        $mem = memory_get_usage();
        $unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        return $isByte ? $mem : round($mem / pow(1024, ($i = floor(log($mem, 1024)))), 2) . ' ' . $unit[$i];
    }

    /**
     * 区间内存量
     * @param $tag
     * @return string
     */
    public static function tagMemory($tag)
    {
        if (isset(self::$memory[$tag . '_start_memory'])) {
            //第二次调用计算内存量
            $mem = memory_get_usage() - self::$memory[$tag . '_start_memory'];
            $unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
            unset(self::$memory[$tag . '_start_memory']);
            return round($mem / pow(1024, ($i = floor(log($mem, 1024)))), 2) . $unit[$i];
        }
        self::$memory[$tag . '_start_memory'] = memory_get_usage();
        return '';
    }

    /**
     * 计算两个标记运行时
     * @param $tag
     * @return mixed
     */
    public static function tagTime($tag)
    {
        if (isset(self::$times[$tag . '_start_time'])) {
            //第二调用计算区间运行时间
            self::$times[$tag . '_end_time'] = microtime(true);
            $time = self::$times[$tag . '_end_time'] - self::$times[$tag . '_start_time'];
            unset(self::$times[$tag . '_start_time']);
            return number_format($time, 6);
        }
        self::$times[$tag . '_start_time'] = microtime(true);
        return 0;
    }

}